package com.iwhalecloud.bss.kite.cucc.order.util;

import com.iwhalecloud.bss.kite.common.constant.TableConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.dataservice.enums.TableConfig;
import com.ztesoft.bss.base.extmapper.BaseMapper;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;

import java.util.Objects;
import java.util.Optional;

/**
 * 数据库表配置工具类
 */
public abstract class TableUtils {

    /**
     * 根据表名或实例类获取Mapper
     *
     * @param tableName
     * @param entityClass
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <E, M extends BaseMapper<E>> M getMapper(String tableName, Class<?> entityClass) {
        TableConfig tableConfig = EnumUtils.getEnum(TableConfig.class, StringUtils.upperCase(tableName));
        if (Objects.nonNull(tableConfig) && Objects.nonNull(tableConfig.getMapperClass())) {
            return (M) SpringUtil.getBean(tableConfig.getMapperClass());
        }
        else {
            String entityName = "";
            if (Objects.nonNull(entityClass)) {
                entityName = entityClass.getSimpleName();
            }
            else {
                entityName = KiteStringUtils.underlineToCamel(tableName);
            }

            return SpringUtil.getBean(StringUtils.uncapitalize(entityName) + TableConfig.DEFAULT_MAPPER_SUFFIX);
        }
    }

    /**
     * 根据表名获取对应的扩展表配置
     *
     * @param tableName
     * @return
     */
    public static TableConfig getExtTableConfig(String tableName) {
        TableConfig tableConfig = EnumUtils.getEnum(TableConfig.class, StringUtils.upperCase(tableName));
        String extTableName = Optional.ofNullable(tableConfig).map(TableConfig::getExtTableName).orElse(null);
        return EnumUtils.getEnum(TableConfig.class, StringUtils.upperCase(extTableName));
    }

    /**
     * 根据实例类获取表名(大写)
     *
     * @param entity
     * @return
     */
    public static String getTableName(Class<?> entity) {
        if (Objects.isNull(entity)) {
            return "";
        }

        TableConsts tableConsts = EnumUtils.getEnum(TableConsts.class, entity.getSimpleName());
        if (Objects.nonNull(tableConsts)) {
            return StringUtils.upperCase(tableConsts.getTableName());
        }
        else {
            return StringUtils.upperCase(KiteStringUtils.camelToUnderline(entity.getSimpleName()));
        }
    }
}
